package com.winit.openapi.sms;

import java.math.BigDecimal;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.SPIException;
import com.winit.common.spi.context.CommandContext;
import com.winit.common.utils.JsonMapper;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.sms.common.SmsUtils;
import com.winit.openapi.sms.validator.AdvanceRechargeFieldValidator;
import com.winit.openapi.util.ValidateUtil;
import com.winit.sms.spi.wallet.CheckAccountCommand;
import com.winit.sms.spi.wallet.WalletService;
import com.winit.sms.spi.wallet.rechargerequisition.RechargeRequisitionService;
import com.winit.sms.spi.wallet.rechargerequisition.command.CreateRechargeRequisitionCommand;
import com.winit.sms.spi.wallet.rechargerequisition.command.QueryExchangeRateCommand;
import com.winit.sms.spi.wallet.rechargerequisition.vo.RechargeRequisitionVo;
import com.winit.ums.spi.distributor.DistributorService;
import com.winit.ums.spi.distributor.command.QueryDistributorByUsernameCommand;
import com.winit.ums.spi.distributor.vo.DistributorVo;
import com.winit.ups.spi.conversion.ConversionService;
import com.winit.ups.spi.conversion.vo.ExchangeRateVo;

/**
 * 分销平台线下充值单
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * keke.xu 	1.0  		2016年4月8日 	Created
 *
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping("/sms/rechargeRequisition")
public class RechargeRequisitionController extends BaseController {

    private static Logger              logger = LoggerFactory.getLogger(RechargeRequisitionController.class);

    @Resource
    private RechargeRequisitionService rechargeRequisitionService;

    @Resource
    private WalletService              walletService;

    @Resource
    private ConversionService          conversionService;
    @Resource
    private DistributorService         distributorService;

    /**
     * 批量导入线下充值单
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/importOffRecharge")
    public String importOffRecharge(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        Object params = requestMsg.getData();
        JSONObject json = null;
        if (params instanceof JSONObject) {
            json = (JSONObject) params;
            AdvanceRechargeFieldValidator.validImportAdvanceRechargeField(json);
        } else {
            logger.info("JSON格式错误: {}", json);
            responseMsg.setCode(ErrorCode.ILLEGAL_JSON_STRING);
            responseMsg.setMsg("JSON格式错误");
            return ERROR;
        }
        CreateRechargeRequisitionCommand command = JsonMapper.fromJson(json.toString(),
            CreateRechargeRequisitionCommand.class);
        command.setCtx(CommandContext.getContext());
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>importAdvanceRecharge:" + command.toString());
        String msg = rechargeRequisitionService.createRechargeRequisition(command);
        // 返回充值单号
        if (StringUtils.isNotBlank(msg)) {
            responseMsg.setCode(ErrorCode.IMPORT_ADVANCE_RECHARGE_IS_ERROR);
            responseMsg.setMsg(msg);
            return ERROR;
        }
        responseMsg.setData(msg);
        return SUCCESS;
    }

    /**
     * 根据批次号查询申请表汇率
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryExchangeRate")
    public String queryExchangeRate(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object params = requestMsg.getData();
        JSONObject json = null;
        if (params instanceof JSONObject) {
            json = (JSONObject) params;
            AdvanceRechargeFieldValidator.validQueryExchangeRateField(json);
        } else {
            logger.info("JSON格式错误: {}", json);
            responseMsg.setCode(ErrorCode.ILLEGAL_JSON_STRING);
            responseMsg.setMsg("JSON格式错误");
            return ERROR;
        }
        QueryExchangeRateCommand command = JsonMapper.fromJson(json.toString(), QueryExchangeRateCommand.class);
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>queryExchangeRate:" + command.toString());
        RechargeRequisitionVo rechargeRequisitionVo = rechargeRequisitionService.queryExchangeRateByBatchNumber(command);
        if (null != rechargeRequisitionVo) {
            responseMsg.setData(rechargeRequisitionVo);
        } else {
            responseMsg.setMsg("不存在此批次号【" + command.getBatchNumber() + "】");
            responseMsg.setCode("-0201025011012");
            return ERROR;
        }
        return SUCCESS;
    }

    /**
     * 查询可用额度
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryAvailableBalance")
    public String queryAvailableBalance(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object params = requestMsg.getData();
        JSONObject json = null;
        if (params instanceof JSONObject) {
            json = (JSONObject) params;
            AdvanceRechargeFieldValidator.validQueryAvailableBalanceField(json);
            Object object = json.get("customerName");
            if (null != object && StringUtils.isNotBlank(object.toString())) {
                QueryDistributorByUsernameCommand command = new QueryDistributorByUsernameCommand();
                command.setUserName(object.toString());
                DistributorVo distributorVo = distributorService.queryDistributorByName(command);
                if (null != distributorVo) {
                    CheckAccountCommand checkAccountCommand = new CheckAccountCommand();
                    checkAccountCommand.setCustomerCode(distributorVo.getCode());
                    BigDecimal usableBalance = walletService.getTotalBalance(checkAccountCommand);
                    responseMsg.setData(usableBalance);
                } else {
                    logger.info("分销商不存在: {}", object.toString());
                    responseMsg.setCode("-0201025011011");
                    responseMsg.setMsg("此客户不存在");
                    return ERROR;
                }
            }
        } else {
            responseMsg.setCode(ErrorCode.ILLEGAL_JSON_STRING);
            responseMsg.setMsg("JSON格式错误");
            return ERROR;
        }
        return SUCCESS;
    }

    /**
     * 根据币种查询充值汇率
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryRechargeExchangeRate")
    public String queryRechargeExchangeRate(@ModelAttribute RequestMsg requestMsg,
                                            @ModelAttribute ResponseMsg responseMsg) {
        com.winit.ups.spi.conversion.command.QueryExchangeRateCommnad command = JSON.parseObject(requestMsg.getData()
            .toString(), com.winit.ups.spi.conversion.command.QueryExchangeRateCommnad.class);
        validQueryExchangeRateByCurrency(SmsUtils.toJsonObject(requestMsg.getData()));
        //获取usp2汇率
        BigDecimal multiplyRate = null;// 汇率
        command.setConversionTypeCode("202");// 货币汇率类型
        try {
            if (command.getCurrencyCode().equals(command.getCurrencyToCode())) {
                multiplyRate = BigDecimal.ONE;
            } else {
                ExchangeRateVo exchangeRateVo = conversionService.queryExchangeRate(command);
                if (null == exchangeRateVo || null == exchangeRateVo.getMultiplyRate()) {
                    responseMsg.setCode("-0201025011013");
                    responseMsg.setMsg("没有查询到汇率");
                    return ERROR;
                }
                multiplyRate = BigDecimal.valueOf(exchangeRateVo.getMultiplyRate());
            }
        } catch (SPIException e) {
            responseMsg.setCode("-0201025011013");
            responseMsg.setMsg("没有查询到汇率");
            return ERROR;
        }
        logger.info("multiplyRate==================》" + multiplyRate);
        responseMsg.setData(multiplyRate);
        return SUCCESS;
    }

    /**
     * 根据币种查询充值汇率验证
     * 
     * @param json
     */
    public void validQueryExchangeRateByCurrency(JSONObject json) {
        ValidateUtil.isNotNull(json, "currencyCode");
        ValidateUtil.isNotNull(json, "currencyToCode");
        ValidateUtil.isNotNull(json, "validDate");
    }
}
